/**
 * Created by jiangyun on 15/11/10.
 */
moduleCommon.factory('ResponseErrorInterceptor', function ($log, $q, $injector, $$CambioConfig, ConstantService) {
    $log.debug('$log is here to show you that this is a regular factory with injection');

    var interceptor = {};
    var authToken = null;
    //var loadingTimeout = null;
    var $http, $timeout, $$CambioConfig, LoadingService, TokenService, LanguageService;
    // optional method
    interceptor.request = function (config) {
        initService();
        if (config.url && config.url.indexOf('ems-system') > 0) {
            LoadingService.show();
        }
        // do something on success
        var requestUrl = config.url;
        config.headers = config.headers || {};
        if ($$CambioConfig.SYSTEM_SPACE == 'CAMBIO') {
            if (ConstantService.getItem("token")) {
                config.headers.Authorization = JSON.stringify({
                    token: ConstantService.getItem('token'),
                    userId: ConstantService.getItem('userId')
                });
            }
        }
        if ($$CambioConfig.SYSTEM_SPACE == 'SZ') {
            if (ConstantService.getItem("authorization")) {
                config.headers.Authorization = ConstantService.getItem("authorization");
            }
        }
        //timeoutShowLoading();
        //var uRLParam = new URLParam();
        ////uRLParam.setVersion("1.1.1", "1");
        //uRLParam.setAuthToken(ConstantService.getItem("authorization"));
        ////uRLParam.setAppType($$CambioConfig.appType);
        ////uRLParam.setClient($$CambioConfig.client);
        //config.url = uRLParam.getUrl(requestUrl);
        //PluginUtil.refresh();
        $log.debug("http request config:" + angular.toJson(config));
        return config;
    };

    var initService = function () {

        if ($http == undefined) {
            $http = $injector.get('$http');
        }

        if ($timeout == undefined) {
            $timeout = $injector.get('$timeout');
        }

        if (TokenService == undefined) {
            TokenService = $injector.get('TokenService');
        }

        if ($$CambioConfig == undefined) {
            $$CambioConfig = $injector.get('$$CambioConfig');
        }

        if (LoadingService == undefined) {
            LoadingService = $injector.get('LoadingService');
        }

        if (LanguageService == undefined) {
            LanguageService = $injector.get('LanguageService');
        }
    };

    //var timeoutShowLoading = function () {
    //    $timeout.cancel(loadingTimeout);
    //    loadingTimeout = $timeout(function () {
    //        $ionicLoading.show();
    //    }, 10000);
    //};
    //
    //var hideResourceLoading = function (config) {
    //    if (config && config.url) {
    //        if (config.url.startWith($$CambioConfig.RESOURCE_URL)) {
    //            $timeout.cancel(loadingTimeout);
    //            $ionicLoading.hide();
    //        }
    //    }
    //};
    //
    //var hideResourceLoadingAndShow = function (config, status) {
    //    if (config && config.url) {
    //        if (config.url.startWith($$CambioConfig.RESOURCE_URL)) {
    //            $timeout.cancel(loadingTimeout);
    //            $ionicLoading.hide();
    //            $$Message.showAlert("请求失败，错误代码:" + status);
    //        }
    //    }
    //};

    // optional method
    interceptor.requestError = function (rejection) {
        // LoadingService.hide();
        //hideResourceLoading(rejection.config, rejection.status);
        $log.debug("http requestError config:" + angular.toJson(rejection));
        LoadingService.hide();
        return $q.reject(rejection);
    };


    // optional method
    interceptor.response = function (response) {
        // initService();
        // LoadingService.hide();
        // do something on success
        //Log.debug("http response url:" + angular.toJson(response.config.url));
        //hideResourceLoading(response.config);
        var d = $q.defer();
        //
        if (response.data.errorCode) {
            if (response.data.errorCode == 200) {
                d.resolve(response);
                LoadingService.hide();
                return d.promise;
            } else {
                return processError(d, response);
            }
        } else {
            d.resolve(response);
            LoadingService.hide();
            return d.promise;
        }
    };

    // optional method
    var processError = function (d, response) {
        //LoadingUtil.stop();
        try {
            if (response.data.errorMessage) {
                Alert.error(response.data.errorMessage);
            } else {
                Alert.error(LanguageService.language('未知错误') + ": " + response.data.errorCode + LanguageService.language('[系统返回错误信息为空]'));
            }
            // //LoadingService.hide();
            d.reject(response);
            LoadingService.hide();
            return d.promise;
        } catch (e) {
            Alert.error(LanguageService.language('未知错误 : [系统返回错误信息为空]') + e);
            LoadingService.hide();
        }


        //switch (response.data.errorCode != 200) {
        //    //case "AUTH_ACTIVE_TIME_OVER_DUE_ERROR":
        //    //    TokenService.refreshToken();
        //    //    break;
        //    default :
        //
        //}
    };

    var setAuthtoken = function (at) {
        authToken = at;
    };

    interceptor.responseError = function (response) {
        initService();
        // Alert.error(LanguageService.language('网络不佳或无网络，请检查网络状态！'));
        LoadingService.hide();
    };

    return {
        'request': interceptor.request,
        'requestError': interceptor.requestError,
        'response': interceptor.response,
        'responseError': interceptor.responseError,
        'setAuthtoken': setAuthtoken
    }
});